import tkinter as tk
from tkinter import filedialog, Label
from tkinterdnd2 import DND_FILES, TkinterDnD
from PIL import Image, ImageTk
import numpy as np
from tensorflow.keras.models import load_model
from model import name

# 加载模型
model = load_model('model.keras')


# 图像预处理
def preprocessing(image_path):
    img = Image.open(image_path).convert('L')  # 转换为灰度图像（'L'表示灰度）
    img = img.resize((28, 28))  # 大小调整为28x28像素
    img = np.array(img) / 255.0  # 将图像转换为NumPy数组，并进行归一化处理
    img = img.reshape(1, 28, 28, 1)  # 其中1表示样本数，28x28表示图像大小，1表示通道数（灰度图像只有一个通道）
    return img


# 调整图像大小并保持纵横比
def resize_image(image, new_width, new_height):
    aspect_ratio = image.width / image.height
    if aspect_ratio > 1:  # 宽图像
        new_height = int(new_width / aspect_ratio)
    else:  # 窄图像
        new_width = int(new_height * aspect_ratio)

    resized_image = image.resize((new_width, new_height), Image.LANCZOS)
    return resized_image


# 分类
def classify(image_path):
    img = preprocessing(image_path)
    prediction = model.predict(img)  # 使用模型进行预测
    pre_class = name[np.argmax(prediction)]  # 获取预测的类别

    img_dis = Image.open(image_path)
    img_dis = resize_image(img_dis, 400, 300)  # 调整图像大小为400x300像素
    tk_img = ImageTk.PhotoImage(img_dis)  # 转换成Tkinter格式
    panel.config(image=tk_img)  # 更新Label组件显示的图像
    panel.image = tk_img  # 绑定新的图像对象到Label组件上

    result.config(text=f"Prediction: {pre_class}")  # 更新结果标签


def upload_file():
    file_path = filedialog.askopenfilename()
    if file_path:
        classify(file_path)


def drop(event):
    file_path = event.data
    classify(file_path)


# 创建主窗口
root = TkinterDnD.Tk()
root.title("服装分类")
root.geometry("800x600")

canvas = tk.Canvas(root, width=800, height=600)  # 创建Canvas来放置背景
canvas.pack(fill='both', expand=True)

bg_path = "background.png"
bg = Image.open(bg_path)
bg = resize_image(bg, 800, 600)  # 调整背景图像大小为窗口大小
bg_photo = ImageTk.PhotoImage(bg)
canvas.create_image(0, 0, image=bg_photo, anchor='nw')

frame = tk.Frame(root, bg='white', bd=5)
canvas.create_window(400, 50, window=frame, anchor="n")  # window 参数指定要嵌入到 Canvas 中的窗口小部件

button = tk.Button(frame, text="Upload an image", command=upload_file, font=('Helvetica', 12))  # 按钮
button.grid(row=0, column=0)

result = Label(frame, text="Prediction: ", font=('Helvetica', 14), bg='white')  # 结果标签
result.grid(row=0, column=1)

panel = Label(canvas, bg='white')  # 在Canvas上放置用于显示图像的Label
canvas.create_window(400, 300, window=panel)  # 位置根据需要调整

root.drop_target_register(DND_FILES)  # 绑定拖拽事件
root.dnd_bind('<<Drop>>', drop)

root.mainloop()  # 运行主循环


